﻿using HandDay.Framework.Core.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;

namespace Handday.Erp.Core
{
    /// <summary>
    /// 注册服务
    /// </summary>
    public static class RegisterServiceExtensions
    {
        /// <summary>
        /// 注册Handday.Erp.*.dll服务
        /// </summary>
        public static IServiceCollection RegisterInterfaceService(this IServiceCollection services)
        {
            var allAssemblyList = System.IO.Directory.GetFiles(AppContext.BaseDirectory, "Handday.Erp.*.dll");
            foreach (var item in allAssemblyList)
            {
                var assembly = Assembly.LoadFrom(item);
                var typeList = assembly.GetExportedTypes().Where(m => m.IsClass && !m.IsAbstract && !m.IsInterface && !m.IsGenericType).ToList();
                foreach (var type in typeList)
                {
                    if (typeof(ITransientDependency).IsAssignableFrom(type))
                    {
                        var interfaceList = type.GetInterfaces().Where(m => m.Name != typeof(ITransientDependency).Name).ToList();
                        interfaceList.ForEach(m => { services.AddTransient(m, type); });
                    }
                    else if (typeof(IScopedDependency).IsAssignableFrom(type))
                    {
                        var interfaceList = type.GetInterfaces().Where(m => m.Name != typeof(IScopedDependency).Name).ToList();
                        interfaceList.ForEach(m => { services.AddScoped(m, type); });
                    }
                    else if (typeof(ISingletonDependency).IsAssignableFrom(type))
                    {
                        var interfaceList = type.GetInterfaces().Where(m => m.Name != typeof(ISingletonDependency).Name).ToList();
                        interfaceList.ForEach(m => { services.AddSingleton(m, type); });
                    }
                }
            }

            return services;
        }
    }
}
